/*
 * addlinkdialog.cpp
 *
 *  Created on: 5.3.2010
 *      Author: aahv
 */

#include "addlinkdialog.h"
#include "ui_addlinkdialog.h"
#include "utils.h"

#include <QLabel>
#include <QPushButton>
#include <QUrl>
#include <QKeyEvent>

AddLinkDialog::AddLinkDialog(QWidget *parent) :
        QDialog(parent),
        ui(new Ui::AddLinkDialog)
{
    setWindowFlags(Qt::Dialog);

    ui->setupUi(this);

    ui->titleEdit->SetExplanation(tr("Title"));
    ui->linkEdit->SetExplanation(tr("Address"));

    QPushButton* okButton = new QPushButton(tr("Ok"));
    connect(okButton, SIGNAL(clicked()), this, SLOT(onOk()));
    QPushButton* cancelButton = new QPushButton(tr("Cancel"));
    connect(cancelButton, SIGNAL(clicked()), this, SLOT(onCancel()));

    QHBoxLayout* buttonLayout = new QHBoxLayout();
    buttonLayout->addWidget(okButton);
    buttonLayout->addWidget(cancelButton);

    ui->verticalLayout->addLayout(buttonLayout);
}

AddLinkDialog::~AddLinkDialog()
{
    delete ui;
}

void AddLinkDialog::setFocus()
{
    QDialog::setFocus();
    if(Utils::smallScreen()) {
        ui->titleEdit->setFocus();
    }
}

void AddLinkDialog::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void AddLinkDialog::keyPressEvent ( QKeyEvent * event  )
{
    if (event->key() == Qt::Key_Context1 )
    {
        onOk();
        event->accept();
    }
    else if(event->key() == Qt::Key_Context2)
    {
        onCancel();
        event->accept();
    }
    else
    {
        QDialog::keyPressEvent(event);
    }
}

void AddLinkDialog::onOk() {
    QUrl url = QUrl::fromUserInput(ui->linkEdit->text());
    if (ui->titleEdit->text().isEmpty()) {
        emit showErrorNote(tr("Title must not be empty."));
    } else if (url == QUrl()) {
        emit showErrorNote(tr("Invalid URL"));
    } else {
        emit addLink(ui->titleEdit->text(), url);
        clear();
        accept();
    }
}

void AddLinkDialog::onCancel() {
    clear();
    reject();
}

void AddLinkDialog::clear() {
    ui->titleEdit->Clear();
    ui->linkEdit->Clear();
    ui->titleEdit->setFocus();
}
